﻿using BaseTool;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using HorizontalAlignment = System.Windows.HorizontalAlignment;
using Image = System.Windows.Controls.Image;

namespace ZerosToDo.SubView;

/// <summary>
/// NotepadWindow.xaml 的交互逻辑
/// </summary>
public partial class NotepadWindow : Window
{
    public NotepadWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Left = App.SuspensionWindow.Left + App.SuspensionWindow.Width;
        Top = App.SuspensionWindow.Top + App.SuspensionWindow.Height - Height;
    }

    private void Window_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        if (IsLoaded is false) { return; }

        if (Visibility is Visibility.Visible)
        {
            Left = App.SuspensionWindow.Left + App.SuspensionWindow.Width;
            Top = App.SuspensionWindow.Top + App.SuspensionWindow.Height - Height;
        }
        else
        {
            Image_AddNewDrag.Visibility = Visibility.Hidden;
        }
    }

    private void AddItem(string _message)
    {
        TextBlock _block = new TextBlock
        {
            Text = _message,
            TextWrapping = TextWrapping.Wrap
        };

        if (_message.Contains(Environment.NewLine))
        {
            _block.HorizontalAlignment = HorizontalAlignment.Left;
        }
        else
        {
            _block.HorizontalAlignment = HorizontalAlignment.Center;
        }
        PART_StackPanel.Children.Add(new NotepadItem(_block));
    }

    private void AddItem(ImageSource _image_source)
    {
        Image _image = new()
        {
            Source = _image_source,
            HorizontalAlignment = HorizontalAlignment.Center,
            MaxHeight = 200
        };
        PART_StackPanel.Children.Add(new NotepadItem(_image));
    }

    public void DeleteItem(NotepadItem _item)
    {
        PART_StackPanel.Children.Remove(_item);
    }

    private void Window_MouseEnter(object sender, MouseEventArgs e)
    {
        CancellDelayClose();
    }

    private async void Window_MouseLeave(object sender, MouseEventArgs e)
    {
        await DelayClose();
    }

    private void Window_DragEnter(object sender, DragEventArgs e)
    {
        DragItemEnter(e);
    }

    private void Window_Drop(object sender, DragEventArgs e)
    {
        _ = DragItemDrop(e);
    }

    #region 延时关闭的机制

    CancellationTokenSource _sourse = new();

    public async Task DelayClose()
    {
        _sourse = new();

        try
        {
            await Task.Delay(3000, _sourse.Token);
            Hide();
        }
        catch (Exception)
        {
            // do nothing
        }
    }


    public void CancellDelayClose()
    {
        _sourse.Cancel();
    }




    #endregion

    public void DragItemEnter(DragEventArgs e)
    {
        foreach (string? item in e.Data.GetFormats())
        {
            Debug.WriteLine(item);
        }

        Debug.WriteLine($"============================");

        e.Effects = DragDropEffects.Copy;
        e.Handled = true;

        Image_AddNewDrag.Visibility = Visibility.Visible;
        Show();
    }

    public async Task DragItemDrop(DragEventArgs e)
    {
        Image_AddNewDrag.Visibility = Visibility.Hidden;
        if (e.Data.GetData(DataFormats.UnicodeText) is string _text)
        {
            try
            {
                using HttpClient client = new HttpClient();
                client.Timeout = TimeSpan.FromSeconds(5);
                HttpResponseMessage response = await client.GetAsync(_text);
                response.EnsureSuccessStatusCode();
                byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();

                // 创建BitmapImage并设置属性
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = new MemoryStream(imageBytes);
                bitmap.EndInit();

                AddItem(bitmap);
            }
            catch (Exception)
            {
                AddItem(_text);
            }
        }
        else if (e.Data.GetData(DataFormats.FileDrop) is string[] _file_path_list)
        {
            foreach (string _path in _file_path_list)
            {
                // 创建 BitmapImage 对象
                BitmapImage _bitmap = new BitmapImage();
                _bitmap.BeginInit();
                _bitmap.CacheOption = BitmapCacheOption.OnLoad; // 按需设置缓存选项
                _bitmap.UriSource = new Uri(_path);
                _bitmap.EndInit();

                AddItem(_bitmap);
            }
        }

        // 滚动到底
        PART_ScrollViewer.ScrollToBottom();
    }

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        // 检查是否按下Ctrl+V
        if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.V)
        {
            // 标记事件已处理，防止其他控件响应
            e.Handled = true;
            PasteFromClipboard();
        }
    }

    public void PasteFromClipboard()
    {
        try
        {
            // 检查剪贴板是否包含文本
            if (Clipboard.ContainsText())
            {
                string text = Clipboard.GetText();
                AddItem(text);
            }
            // 检查剪贴板是否包含图像
            else if (Clipboard.ContainsImage())
            {
                BitmapSource image = Clipboard.GetImage();
                AddItem(image);
            }
            // 滚动到底
            PART_ScrollViewer.ScrollToBottom();
        }
        catch (Exception ex)
        {
            BaseLogManager.SendLog(LogLevel.Error, ex.Message, $"{ex}");
        }
    }
}
